package edu.faytechcc.csc289.gui;

import edu.faytechcc.csc289.data.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

/**
 * This class creates the Sales Associate panel
 *
 * Mar 27, 2014
 *
 * @author William Robles
 */
public class SalesView extends JPanel
{

    private final Dimension inventoryTableSize = new Dimension(1000, 200);
    private final Dimension scrollPaneSize = new Dimension(320, 140);

    private JPanel selectionPanel;

    private JButton exitButton, addButton, removeButton, refreshButton,
            checkoutButton;
    private JTable inventoryTable;
    private JScrollPane inventoryScrollPane, cartScrollPane;

    private JLabel costLabel, nameLabel, retailLabel, gameLabel,
            descriptionLabel, qtyLabel;

    private JTextField descriptionTextField, nameTextField, costTextField,
            retailTextField, qtyTextField;

    private JTextArea cartJTextArea;

    private final ArrayList<Item> cartList = new ArrayList<>();

    private ImageIcon gameImage = new ImageIcon();
    private ImageIcon refreshImage;

    private SimulacraDbConnection sDb;

    private ResultSet invResults;

    private DataDisplay dD;

    public SalesView()
    {
        selectionPanel = new JPanel();
        selectionPanel.setLayout(new BorderLayout());

        this.sDb = new SimulacraDbConnection();
        this.setLayout(new BorderLayout());

        dD = new DataDisplay();

        buildInventoryDisplay();
        buildGameInfoDisplay();
        buildCheckoutCart();
        buildBottomPanel();
    }

    /**
     * buildInventoryDisplay method creates the inventoryTable and displays
     */
    private void buildInventoryDisplay()
    {
        inventoryTable = new JTable(dD.buildTable(invResults, sDb));
        inventoryTable.getTableHeader().setReorderingAllowed(false);
        inventoryTable.removeColumn(inventoryTable.getColumnModel().getColumn(
                                          inventoryTable.getColumnCount() - 1));
        inventoryTable.getClass();
        inventoryTable.setPreferredScrollableViewportSize(inventoryTableSize);
        inventoryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        inventoryTable.setAutoCreateRowSorter(true);

        inventoryTable.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.
                                                                        RAISED));

        inventoryTable.getSelectionModel().addListSelectionListener(new
                                                            SelectionListener());

        inventoryScrollPane = new JScrollPane(inventoryTable);

        this.add(inventoryScrollPane, BorderLayout.NORTH);
    }

    /**
     * buildSelectionPanel method creates the selection panel that includes the
     * gameImage and the sales JTextArea
     */
    private void buildGameInfoDisplay()
    {
        JPanel temp = new JPanel();
        temp.setLayout(new GridLayout(5, 1));
        JPanel temp2 = new JPanel(new FlowLayout(FlowLayout.LEADING));

        refreshImage = new ImageIcon("res/refresh.png");

        addButton = new JButton("Add");
        addButton.setToolTipText("Add new item");
        addButton.addActionListener(new ButtonListener());
        removeButton = new JButton("Remove");
        removeButton.setToolTipText("Remove item");
        removeButton.addActionListener(new ButtonListener());
        refreshButton = new JButton(refreshImage);
        refreshButton.setToolTipText("Refresh Inventory Table");
        refreshButton.addActionListener(new ButtonListener());

        gameLabel = new JLabel(gameImage);

        temp.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));

        costLabel = new JLabel("Cost: ");
        retailLabel = new JLabel("Retail Price: ");
        nameLabel = new JLabel("Name: ");
        descriptionLabel = new JLabel("Description: ");
        qtyLabel = new JLabel("Quantity: ");

        costTextField = new JTextField(7);
        costTextField.setEditable(false);
        retailTextField = new JTextField(7);
        retailTextField.setEditable(false);
        nameTextField = new JTextField(23);
        nameTextField.setEditable(false);
        qtyTextField = new JTextField(3);
        qtyTextField.setEditable(false);
        descriptionTextField = new JTextField(20);
        descriptionTextField.setEditable(false);

        temp2.add(nameLabel);
        temp2.add(nameTextField);
        temp.add(temp2);

        temp2 = new JPanel(new FlowLayout(FlowLayout.LEADING));
        temp2.add(descriptionLabel);
        temp2.add(descriptionTextField);
        temp.add(temp2);

        temp2 = new JPanel(new FlowLayout(FlowLayout.LEADING));
        temp2.add(costLabel);
        temp2.add(costTextField);
        temp2.add(retailLabel);
        temp2.add(retailTextField);
        temp.add(temp2);

        temp2 = new JPanel(new FlowLayout(FlowLayout.LEADING));
        temp2.add(qtyLabel);
        temp2.add(qtyTextField);
        temp.add(temp2);

        temp2 = new JPanel(new FlowLayout(FlowLayout.LEADING));
        temp2.add(addButton);
        temp2.add(removeButton);
        temp2.add(refreshButton);
        temp.add(temp2);

        selectionPanel.add(temp, BorderLayout.WEST);
        selectionPanel.add(gameLabel, BorderLayout.CENTER);

        this.add(selectionPanel, BorderLayout.CENTER);
    }

    /**
     * buildImageUploadPanel method creates the panel that allows selection of
     * image to be uploaded
     */
    private void buildCheckoutCart()
    {
        cartJTextArea = new JTextArea();
        cartJTextArea.setEditable(false);
        cartJTextArea.setLineWrap(true);

        cartScrollPane = new JScrollPane(cartJTextArea);
        cartScrollPane.setPreferredSize(scrollPaneSize);
        cartScrollPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.
                                                                        RAISED));

        selectionPanel.add(cartScrollPane, BorderLayout.EAST);
    }

    /**
     * buildBottomPanel method creates the lower panel with an exit button
     */
    private void buildBottomPanel()
    {
        JPanel temp = new JPanel(new FlowLayout(FlowLayout.LEADING));
        JPanel temp2 = new JPanel(new BorderLayout());
        JLabel salesLabel = new JLabel("Sales", SwingConstants.CENTER);
        salesLabel.setFont(new Font("Serif", Font.BOLD, 25));
        temp2.add(salesLabel, BorderLayout.CENTER);

        temp2.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));

        exitButton = new JButton("Exit");
        exitButton.addActionListener(new ButtonListener());
        temp.add(exitButton);
        temp2.add(temp, BorderLayout.WEST);

        temp = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        checkoutButton = new JButton("Checkout");
        checkoutButton.addActionListener(new ButtonListener());
        temp.add(checkoutButton);
        temp2.add(temp, BorderLayout.EAST);

        this.add(temp2, BorderLayout.SOUTH);
    }

    /**
     * addToCart method adds item to cart
     */
    private void addToCart()
    {
        invResults = sDb.getInventory();
        Item temp = new Item();

        try
        {
            invResults.absolute(inventoryTable.convertRowIndexToModel(
                    inventoryTable.getSelectedRow()) + 1);

            temp.setAbsolutePos(inventoryTable.convertRowIndexToModel(
                    inventoryTable.getSelectedRow()) + 1);
            temp.setQuantity(invResults.getInt("Quantity"));
            temp.setItemName(invResults.getString("Item Name"));
            temp.setRetailPrice(invResults.getBigDecimal("Retail Price"));

            if (temp.getQuantity() > 0)
            {
                temp.setQuantity(temp.getQuantity() - 1);

                invResults.updateInt("Quantity", temp.getQuantity());
                invResults.updateRow();

                cartList.add(temp);
                cartJTextArea.setText("");

                for (Item cartI : cartList)
                {

                    cartJTextArea.append(cartI.getItemName() + "\t" + "\t"
                            + cartI.getRetailPrice() + "\n");
                }

            }
            else
            {
                JOptionPane.showMessageDialog(null,
                        "ERROR: There are no items left",
                        "Error Message",
                        JOptionPane.ERROR_MESSAGE);
            }

            invResults.close();
        }
        catch (SQLException ex)
        {
            System.err.println("ERROR: " + ex.getMessage());
            System.exit(24);
        }

        dD.refreshTable(inventoryTable, invResults, sDb);
        clearFields();
    }

    /**
     * the checkoutMethod calculates total and confirms sale
     */
    private void checkout(ActionEvent ae)
    {
        if (!dD.confirmAction(ae))
        {
            invResults = sDb.getInventory();

            try
            {
                for (Item cartI : cartList)
                {
                    invResults.absolute(cartI.getAbsolutePos());
                    invResults.updateInt("Quantity", cartI.getQuantity() + 1);
                    invResults.updateRow();
                }

                cartJTextArea.setText("");
                cartList.clear();
                invResults.close();
            }
            catch (SQLException ex)
            {
                System.err.println("ERROR: " + ex.getMessage());
                System.exit(24);
            }

            dD.refreshTable(inventoryTable, invResults, sDb);
            clearFields();
        }

    }

    /**
     * removeItem method removes the selected item from the database
     */
    private void removeFromCart()
    {
        invResults = sDb.getInventory();

        try
        {
            invResults.absolute(inventoryTable.getSelectedRow() + 1);
            invResults.deleteRow();

            invResults.close();
        }
        catch (SQLException ex)
        {
            System.err.println("ERROR: " + ex.getMessage());
            System.exit(24);
        }

        dD.refreshTable(inventoryTable, invResults, sDb);
    }

    /**
     * clearTextFields methods clears textfields and image
     */
    private void clearFields()
    {
        nameTextField.setText("");
        descriptionTextField.setText("");
        nameTextField.setText("");
        costTextField.setText("");
        retailTextField.setText("");
        qtyTextField.setText("");
        gameImage = null;
        gameLabel.setIcon(gameImage);
    }

    /**
     * showSelectedPic method displays the selected item from table picture
     */
    private void showSelectedItem()
    {
        invResults = sDb.getInventory();

        try
        {
            invResults.absolute(inventoryTable.convertRowIndexToModel(
                    inventoryTable.getSelectedRow()) + 1);
            Blob imageBlob = invResults.getBlob("Picture");
            byte[] bytes = imageBlob.getBytes(1, (int) imageBlob.length());
            imageBlob.free();

            nameTextField.setText(invResults.getString("Item Name"));
            descriptionTextField.setText(invResults.getString("Description"));
            costTextField.setText(invResults.getBigDecimal("Cost").toString());
            retailTextField.setText(invResults.getBigDecimal("Retail Price").
                                                                    toString());
            qtyTextField.setText(invResults.getString("Quantity"));

            gameImage = new ImageIcon(bytes);

            gameLabel.setIcon(gameImage);

            invResults.close();
        }
        catch (SQLException ex)
        {
            System.err.println("ERROR: " + ex.getMessage());
            System.exit(24);

        }
    }

    private class SelectionListener implements ListSelectionListener
    {

        public SelectionListener()
        {

        }

        @Override
        public void valueChanged(ListSelectionEvent lse)
        {
            if (inventoryTable.getSelectedRow() != -1)
            {
                showSelectedItem();
            }
        }
    }

    private class ButtonListener implements ActionListener
    {

        public ButtonListener()
        {
        }

        @Override
        public void actionPerformed(ActionEvent ae)
        {
            if (ae.getSource() == exitButton)
            {
                Component c = (Component) ae.getSource();

                JFrame frame = (JFrame) SwingUtilities.getRoot(c);

                frame.dispose();
            }
            else if (ae.getSource() == addButton)
            {
                addToCart();
            }
            else if (ae.getSource() == removeButton)
            {
                removeFromCart();
            }
            else if (ae.getSource() == refreshButton)
            {
                dD.refreshTable(inventoryTable, invResults, sDb);
            }
            else if (ae.getSource() == checkoutButton)
            {
                checkout(ae);
            }
        }
    }
}
